package com.ruoyi.redis;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

import java.nio.charset.Charset;

/**
 * @Author: LvKinfy
 * @Date: 2019/3/17 22:39
 * @Version 1.0
 */
public class FastJsonRedisSerializer<T> implements RedisSerializer<T> {
  public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
  private Class<T> clazz;

  public FastJsonRedisSerializer(Class<T> clazz) {
    super();
    this.clazz = clazz;
  }

  @Override
  public byte[] serialize(T t) throws SerializationException {
    if (t == null) {
      return new byte[0];
    }
    if (t instanceof String) {
      return ((String) t).getBytes(DEFAULT_CHARSET);
    } else if (t instanceof Number) {
      return String.valueOf(t).getBytes(DEFAULT_CHARSET);
    } else {
      return JSON.toJSONString(t, SerializerFeature.UseSingleQuotes, SerializerFeature.DisableCheckSpecialChar, SerializerFeature.NotWriteRootClassName, SerializerFeature.DisableCircularReferenceDetect, SerializerFeature.SkipTransientField).getBytes(DEFAULT_CHARSET);
    }
  }

  @Override
  public T deserialize(byte[] bytes) {
    if (bytes == null || bytes.length <= 0) {
      return null;
    }
    String str = new String(bytes, DEFAULT_CHARSET);
    if (str.contains("{") || str.contains("[")) {
      return JSON.parseObject(str, clazz);
    } else {
      return (T) str;
    }
  }
}
